package com.dgut.legalservice.controller;

import com.dgut.legalservice.domain.Approval;
import com.dgut.legalservice.domain.Order;
import com.dgut.legalservice.domain.User;
import com.dgut.legalservice.domain.attachment.Attachment;
import com.dgut.legalservice.service.ApprovalService;
import com.dgut.legalservice.service.IAttachmentService;
import com.dgut.legalservice.service.OrderService;
import com.dgut.legalservice.tool.FileTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/approval")
public class ApprovalController {
    @Autowired
    private ApprovalService approvalService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private IAttachmentService attachmentService;
    /**
     * 添加approval并设置订单状态 服务商更改状态
     * @param approval
     * @param orderId
     * @return
     */
    @RequestMapping("/update/{orderId}")
    public ModelAndView updateAppr(Approval approval, @RequestParam(name = "uploadFile") MultipartFile uploadFile, @PathVariable Integer orderId, HttpServletRequest request) throws IOException {
        Integer userId = (Integer) request.getSession().getAttribute("userId");
        Map<String, String> map = FileTool.fileUpload(uploadFile, request);
        if (map != null) {
            Attachment attachment = new Attachment(map.get("name"), map.get("path"), null, userId, userId);
            attachmentService.addAttachment(attachment);
            approval.setAttGroupId(attachment.getId());
        }

        approval.setAuditUserId(userId);//设置接收人

        int i = approvalService.setFirStatus(approval, orderId);
        Order order = new Order();
        order.setStatus("订单处理完成");
        orderService.setFirStatus(order,orderId);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("forward:/order/allser");

        return mv;
    }

    /**
     * 查找审核表
     * @param orderId
     * @return
     */
    @RequestMapping("/find")
    public ModelAndView findAppr(Integer orderId){
        List<Approval> approvals = approvalService.selectById(orderId);
        ModelAndView mv = new ModelAndView();
        mv.addObject("approvals",approvals);
        mv.setViewName("/user/order-list.html");
        return mv;
    }


}
